package controller.exception;

import controller.common.StaticConstant;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.session.InvalidSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import response.CommonResult;
import util.JsonUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * Created by Administrator on 2017/12/1.
 */
public class DefaultExceptionHandler implements HandlerExceptionResolver {
    private static Logger log = LoggerFactory.getLogger(DefaultExceptionHandler.class);


     private   String loginUrl;

    public String getLoginUrl() {
        return loginUrl;
    }

    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }

    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
        log.warn("统一异常处理:");
        exception.printStackTrace();


        ModelAndView mv = new ModelAndView();

        if (exception instanceof UnauthenticatedException) { // 未登录
            mv.setViewName(getLoginUrl());
            return mv;
        }
        if (exception instanceof UnauthorizedException) { // shiro没有权限异常
            mv.setViewName("welcome/error/unauthorized");
            return mv;
        }

        if (exception instanceof InvalidSessionException) {// shiro会话已过期异常
            mv.setViewName("/4044.jsp");
            return mv;
        }

        String errorMessage = exception.getMessage();
        if (exception instanceof UncategorizedSQLException) {
            System.out.println("sql 异常");
            
            UncategorizedSQLException uncategorizedSQLException = (UncategorizedSQLException) exception;
            errorMessage = uncategorizedSQLException.getSQLException().getMessage();
        }


        //是否是ajax请求
        if (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {

            if ("true".equals(request.getHeader("_superAjax"))) {//是否是由superAjax提交
                CommonResult commonResult = new CommonResult();
                commonResult.setError();
                commonResult.setMessage(errorMessage);
                errorMessage = JsonUtil.obj2Json(commonResult);
                setJsonResponse(response, errorMessage);
                return mv;
            } else if ("true".equals(request.getParameter("_modalRemote"))) {//是否是 modal 远程加载页面
                //修改bootstrap源码，modal 远程加载页面时多加一个标志参数（_modalRemote=true）。
                //this.$element.find('.modal-content').load(this.options.remote,{_modalRemote:true},$.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this))

                mv.addObject(StaticConstant.ERROR_MESSAGE,errorMessage);
                mv.setViewName(StaticConstant.ERROR_DLG);
                return mv;
            }
        }

        mv.addObject(StaticConstant.ERROR_MESSAGE,errorMessage);
        mv.setViewName(StaticConstant.ERROR_PAGE);
        return mv;
    }

    public void setJsonResponse(HttpServletResponse response, String data) {
        response.setStatus(HttpStatus.OK.value()); //设置状态码
        response.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
        response.setCharacterEncoding("UTF-8"); //避免乱码
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        try {
            OutputStream out = response.getOutputStream();
            out.write(data.getBytes("UTF-8"));
            out.flush();
        } catch (Exception e) {
            log.error("【Manual】=>{}", e.getMessage());
        }


    }


}
